﻿using System;
using System.Collections.Generic;
using System.Linq;
using NetSurveillance.WebApp.DataServices.Models;
using ServiceStack.OrmLite;

namespace NetSurveillance.WebApp.DataServices.Implementations
{
    public class VirusEmbedsService : BaseService<VirusEmbedRule>
    {
        public VirusEmbedsService(string connStr, IOrmLiteDialectProvider provider = null)
            : base(connStr, provider)
        {
        }

        public ServiceResult SaveTaskVirusEmbedRule(long taskId, long[] veRuleIds)
        {
            using (var db = DbFactory.OpenDbConnection())
            {
                using (var trans = db.OpenTransaction())
                {
                    try
                    {
                        var taskVERules = db.Select<TaskVirusEmbedRule>(p => p.TaskId == taskId);
                        foreach (var taskVERule in taskVERules)
                        {
                            taskVERule.StatusToken = veRuleIds.Contains(taskVERule.VirusEmbedId) ? 1 : 0;
                            taskVERule.LastModifiedTime = DateTime.Now;
                            db.Save(taskVERule);
                        }
                        bool isDbEmpty = !taskVERules.Any();
                        foreach (long veRuleId in veRuleIds.Where(p => isDbEmpty || taskVERules.All(m => m.VirusEmbedId != p)))
                        {
                            var taskVERule = new TaskVirusEmbedRule { TaskId = taskId, VirusEmbedId = veRuleId };
                            db.Save(taskVERule);
                        }
                    }
                    catch (Exception ex)
                    {
                        //todo: log this ex.
                        trans.Rollback();
                        return new ServiceResult(false, ex.Message);
                    }
                    trans.Commit();
                }
                return ServiceResult.SuccessResult;
            }
        }

        public IList<long> GetTaskVirusEmbedRuleIds(long taskId)
        {
            using (var db = DbFactory.OpenDbConnection())
            {
                const string searchSql =
                    @"select ""VirusEmbedId"" from ""TaskVirusEmbedRules"" 
                        where ""StatusToken"" != 0 and ""TaskId""={0}";
                var taskVERuleIds = db.List<long>(searchSql.Params(taskId));
                return taskVERuleIds;
            }
        }
    }
}
